package com.spring.provideronetest.test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @auther zhangxiangtao
 * @date 2021/1/12
 */
public class Lazy {

	private static boolean sf = false;
	private Lazy(){
		if(sf == false){
			sf =true;
			System.out.println(Thread.currentThread().getName());
		}else {
			throw new RuntimeException("不能使用反射");
		}

	}

	private volatile static Lazy lazy =null;
	//双重检测锁模式的懒汉式DCL模式
	public static Lazy getLazy(){
		if(lazy == null){
			synchronized (Lazy.class){
				if(lazy == null){
					lazy = new Lazy();
				}
			}
		}


		return lazy;
	}

	public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException, ClassNotFoundException {
//		for(int i=0;i < 10;i++){
//			new Thread(()->{Lazy.getLazy();}).start();
//		}
//		Constructor<Lazy> lazyConstructors = Lazy.class.getConstructor();
		Class lazyClass = Class.forName("com.spring.provideronetest.test.Lazy");
		System.out.println(lazyClass);
		Constructor<Lazy> lazyConstructor = Lazy.class.getDeclaredConstructor(null);
		Field sf = Lazy.class.getDeclaredField("sf");
		sf.setAccessible(true);
		lazyConstructor.setAccessible(true);
		Lazy lazy = lazyConstructor.newInstance();
		sf.set(lazy,false);
		Lazy lazy2 = lazyConstructor.newInstance();
		System.out.println(lazy);
		System.out.println(lazy2);
//		System.out.println(lazyConstructors);

		Constructor<Lazy> lazys=Lazy.class.getDeclaredConstructor(null);
		lazys.setAccessible(true);
		Field sf1 = Lazy.class.getDeclaredField("sf");
		sf1.setAccessible(true);
		sf1.set(lazy2,false);
		Lazy a = lazys.newInstance();

		System.out.println(a);

		
	}

}

class LazyInner{

	 static class InnerClass{
		private static final LazyInner lazy = new LazyInner();
	}

	public static final LazyInner getInstance(){
		return InnerClass.lazy;
	}
}

enum LazyEnum{
	LAZY_ENUM;
	public LazyEnum getLazyEnum(){
		return LAZY_ENUM;
	}
}
